package com.jnc.rest.core.base.controller;

import com.jnc.rest.constant.SysConstant;
import com.jnc.rest.core.base.dto.BaseResp;
import com.jnc.rest.core.base.dto.QueryReq;
import com.jnc.rest.core.base.dto.RespCode;
import com.jnc.rest.core.error.AuthException;
import com.jnc.rest.util.AESUtil;
import com.jnc.rest.util.TokenUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: jjn
 * @Date: 2018/8/11
 * @Description: 基础Controller类
 */
@Slf4j
public class BaseController {

    /**
     * 将前台传递过来的日期格式的字符串，自动转化为Date类型
     */
    @InitBinder
    public void initBinder(WebDataBinder binder){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }


    protected String getUserName(HttpServletRequest request){
        //获取当前登录账号
        String token = request.getHeader(SysConstant.TOKEN_KEY);
        if(StringUtils.isBlank(token)){
            throw new AuthException("Invalid access token: " + token);
        }
        return getUserName(token);
    }

    /**
     * 响应表格数据
     * @param list
     * @return
     */
    @SuppressWarnings("unchecked")
    protected BaseResp getTableData(List<?> list){
        BaseResp resp = new BaseResp();
        Map<String, Object> map = new HashMap<>(2);
        map.put("rows", list);
        map.put("total", new PageInfo(list).getTotal());
        resp.setCode(RespCode.SUCCESS.getCode()).setData(map);
        return resp;
    }

    /**
     * 初始化请求分页数据
     * @param req
     */
    protected void initPage(QueryReq req){
        Integer pageNum = req.getPageNo() == null ? 1 : req.getPageNo();
        Integer pageSize = req.getPageSize() == null ? 10 : req.getPageSize();
        PageHelper.startPage(pageNum, pageSize, req.getOrderBy());
    }

    @SuppressWarnings("rawtypes")
    public BaseResp toResp(int rows){
        return rows > 0 ? BaseResp.success("操作成功") : BaseResp.fail("操作失败");
    }

    /**
     * 根据token，获取登录用户名
     * @param token
     * @return
     */
    private String getUserName(String token){
        try {
            String decode = AESUtil.aesDecrypt(token, TokenUtil.salt);
            if(StringUtils.isNotBlank(decode)){
                String[] split = decode.split(":");
                return split[0];
            }
        } catch (Exception e) {
            log.error("parse token error: {}", e);
            e.printStackTrace();
        }
        throw new AuthException("Invalid access token: " + token);
    }
}
